package clientGUI.studentGUI;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedList;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

//COMMENTED OUT A LINE OR TWO OR THREE OR A MILION TO ALLOW TESTING

import clientApp.*;
import clientGUI.PassBackToable;
import clientGUI.SelectCoursesGUI_Catalog;


public class StudentMainGUI implements PassBackToable
{
	private static VirtualAdvisor myVA;
	private static Plan 	myPlan;
	private boolean			blankPlan;
	private static JFrame	frame;
	// the main schedule panel
	private static JPanel	mainPanel;
	private static boolean saved;
	private static JPanel mainStuPane;
	
	// constructor
	public StudentMainGUI(VirtualAdvisor VA)
	{
		myVA		= VA;
		myPlan		= new Plan("New Plan");
		blankPlan	= true;
		mainPanel	= new JPanel();
		saved		= true;
		
		// display the frame generated by createPaneSTUDENT()
		frame		= GUI_Function_Library.displayPane("Student Main Page", createPaneSTUDENT(VA.getName()), true);
	}
	
	/**
	 * silly workaround for buttons
	 * @param newPane
	 */
	private void resetSchedulePane(JPanel newPane)
	{
		mainPanel = newPane;
	}
	
	/**
	 * loadedSchedule(Plan plan)
	 * returns a JPanel representation of the student's plan
	 * 
	 * Precondition:	
	 * Postcondition:	
	 * @param plan Student Plan loaded in
	 * @return JPanel representation of Plan
	 */
	private JPanel loadedSchedule(Plan plan)
	{
		JPanel schedulePane = new JPanel();
		schedulePane.setLayout(new BoxLayout(schedulePane, BoxLayout.PAGE_AXIS));
		final LinkedList<JPanel> semesterPanels = new LinkedList<JPanel>();
		
		// for every semester in the plan, create a panel with labels
		for(Semester currentSemester: plan.getSemesters())
		{
			// create the semester pane
			final JPanel semesterPane = new JPanel();
			semesterPane.setLayout(new BoxLayout(semesterPane, BoxLayout.PAGE_AXIS));
			semesterPane.setBorder(BorderFactory.createTitledBorder(currentSemester.getYear() + " " + ProjectConstants.getSeasonString(currentSemester.getSeason())));
			
			// create title labels for semester pane
			JLabel courseNameTitleLabel	= new JLabel("Course Name");
			JLabel creditNumTitleLabel	= new JLabel ("# Credits");
			JLabel emptyTitleLabel		= new JLabel();
			JLabel gradeTitleLabel		= new JLabel("Letter Grade");
			// create a semester title pane
			JPanel semesterTitlePane	= new JPanel(new GridLayout(1,4));
			semesterTitlePane.setBorder(BorderFactory.createLineBorder(null));
			semesterTitlePane.add(courseNameTitleLabel);
			semesterTitlePane.add(emptyTitleLabel);
			semesterTitlePane.add(creditNumTitleLabel);
			semesterTitlePane.add(gradeTitleLabel);
			// add titles to the semester pane
			semesterPane.add(semesterTitlePane);
			
			// for every course record in the semester, create a JPanel
			for(CourseRecord currentCourse: currentSemester.getCourseRecords())
			{
				// create course pane
				JPanel coursePane		= new JPanel(new GridLayout(1,4));
				JLabel courseNameLabel	= new JLabel(currentCourse.getCourseID());
				JLabel emptyLabel		= new JLabel();
				
				//JLabel courseCreditNumLabel = new JLabel(Integer.toString(myVA.getCatalog().getCourse(currentCourse.getCourseID()).getNumCreds()));
				JLabel courseCreditNumLabel = new JLabel(Double.toString(myVA.getNumCredits(currentCourse.getCourseID())));
//				JTextField courseGradeField = new JTextField("E");
				String[] gradeChoices = {"A", "B", "C", "D", "E", "(F)ail", "(I)ncomplete", "(P)ass", "(W)ithdrawn"};
				JComboBox courseGradeDropdown = new JComboBox(gradeChoices);
				
				String selection = "I";
				switch (currentCourse.getGrade()) {
				case 'A': selection = Character.toString(currentCourse.getGrade());
				case 'E': break;
				case 'F': selection = "(F)ail"; break;
				case 'I': selection = "(I)ncomplete"; break;
				case 'P': selection = "(P)ass"; break;
				case 'W': selection = "(W)ithdrawn"; break;
				}

				courseGradeDropdown.setSelectedItem(selection);
				
				final String courseID = currentCourse.getCourseID();
				final char grade = ((((String)(courseGradeDropdown.getSelectedItem())).length()) == 1) ?
						((String)(courseGradeDropdown.getSelectedItem())).charAt(0) :
							((String)(courseGradeDropdown.getSelectedItem())).charAt(1);
				final int season = currentSemester.getSeason();
				final int year = currentSemester.getYear();
				courseGradeDropdown.addActionListener(new ActionListener() {	
					public void actionPerformed(ActionEvent e) {
						myVA.changeCourseRecordGrade(myPlan.getPlanName(), season, year, courseID, grade);
					}
				});
				
				// add courses to the course pane
				coursePane.add(courseNameLabel);
				coursePane.add(emptyLabel);
				coursePane.add(courseCreditNumLabel);
//				coursePane.add(courseGradeField);
				coursePane.add(courseGradeDropdown);

				// add course to semester
				semesterPane.add(coursePane);
			}
			
			// create a button to remove the semester
			// and add functionality
			JButton removeSemesterButton = new JButton("Remove Semester");
			removeSemesterButton.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e)
				{
					semesterPanels.remove(semesterPane);
				}
			});
			
			// add things to the semester
			semesterPanels.add(semesterPane);
			schedulePane.add(semesterPane);
		}

		
		// add scrolling to the schedule viewer
		JScrollPane scheduleScrollPane = new JScrollPane(schedulePane);
//		scheduleScrollPane.setPreferredSize(new Dimension(350, 300));

		// create final, returnable JPanel
		JPanel returnPane = new JPanel();
		returnPane.setBorder(BorderFactory.createTitledBorder(plan.getPlanName()));
		returnPane.add(scheduleScrollPane);
		
		// return promised panel
		return returnPane;
	}
	
	/**
	 * Precondition:	
	 * Postcondition:	
	 * 
	 * empty!! generates new schedule upon login
	 * @return
	 */
	private JPanel newSchedulePane()
	{
		JPanel mainPanel = new JPanel();
		JLabel mainLabel = new JLabel("Nothing Yet. Click the \"Add Course\" button to add a course!");
		mainPanel.add(mainLabel);
		return mainPanel;
	}


	/**
	 * main page for students, display schedule
	 * Precondition:	username is valid
	 * Postcondition:	
	 * 
	 * @param name student username
	 * @return JPanel of student welcome page
	 */
	private JPanel createPaneSTUDENT(String name)
	{
		// order: Center, N,S,W (East DNE)
		mainStuPane = new JPanel(new BorderLayout());
		
		// Center - display schedule panel
		mainPanel = newSchedulePane();

		// North - greeting, save/load, help, logout
		JPanel accountPane = new JPanel(new GridLayout(1,6));
		// greeting
		JLabel greetingLabel = new JLabel(name + "\'s Schedule");
		// buttons - save load help logout
		JButton newButton	= new JButton("New Plan");
		JButton saveButton	= new JButton("Save Plan");
		JButton loadButton	= new JButton("Load Plan");
		JButton helpButton	= new JButton("Help");
		JButton exitButton	= new JButton("Log Out");
		// add all
		accountPane.add(greetingLabel);
		accountPane.add(newButton);
		accountPane.add(saveButton);
		accountPane.add(loadButton);
		accountPane.add(helpButton);
		accountPane.add(exitButton);
			
		// South - feedback panel
		JPanel feedbackPane = new JPanel();
		JLabel feedbackLabel = new JLabel("Feedback:");
		final JTextArea feedbackArea = new JTextArea("Good so far-- blankity");
		feedbackPane.add(feedbackLabel);
		feedbackPane.add(feedbackArea);
				
		// WEST - add/edit course, audit report panel
		JPanel scheduleButtonPane	= new JPanel(new GridLayout(3,1));
		JButton addCourseButton		= new JButton("Add Course(s) to a Semester");
		JButton editCourseButton	= new JButton("Edit/Remove Course(s) from a Semester");
		JButton auditButton			= new JButton("Audit Report");
		scheduleButtonPane.add(addCourseButton);
		scheduleButtonPane.add(editCourseButton);
		scheduleButtonPane.add(auditButton);
		addCourseButton.setActionCommand(	"add course");
		editCourseButton.setActionCommand(	"edit course");
		auditButton.setActionCommand(		"report audit");
		
		// buttons add actions
		newButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0)
			{
				saved = false;
				mainPanel.setVisible(false);
				try {
					String newPlanName = JOptionPane.showInputDialog("Enter New Plan Name");
					if(myVA.getPlanNames() != null && myVA.getPlanNames().contains(newPlanName))	
						throw new Exception("Please enter a unique plan name");
					else
					{
						myPlan = new Plan(newPlanName);
						blankPlan = false;
						JPanel mySchedPane = loadedSchedule(myPlan);
						resetSchedulePane(mySchedPane);
						mainStuPane.add(mySchedPane, BorderLayout.EAST);
						myVA.addPlan(myPlan);
						/* Edited by Rotem to reflect the current date */
						myVA.addSemesterToPlan(newPlanName, new Semester());
						/*End code edited by Rotem */
						mainStuPane.revalidate();
					}
				} catch (Exception e) {
					GUI_Function_Library.exceptionHandler(e);
				}
			}
		});
		saveButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				if (blankPlan == true) {
					JOptionPane.showMessageDialog(null, "Please load an existing plan or click \"New Plan\" to begin.");
				} else {
					saved = true;
					try {
						VirtualAdvisor.saveUser(myVA.getName());
						JOptionPane.showMessageDialog(null, "Your plan has been saved!");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
				// SHOULD INTERACT WITH VA
			}
		});
		loadButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				saved = false;
				mainPanel.setVisible(false);
				try {
					myPlan = StudentLoad.getPlanFromUser(myVA);
					blankPlan = false;
					JPanel mySchedPane = loadedSchedule( myPlan);
					resetSchedulePane( mySchedPane);
					mainStuPane.add(mySchedPane, BorderLayout.EAST);
					mainStuPane.revalidate();
				} catch (Exception e) {
					GUI_Function_Library.exceptionHandler("Load Plan", e);
				}				
			}
		});
		helpButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				HelpGUI helpWindow = new HelpGUI();
			}
		});
		exitButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				if(!saved)
				{
					int exitDialog = JOptionPane.showConfirmDialog(null, "You have not saved this plan yet.\nDo you still want to exit?");	
					if(exitDialog == JOptionPane.YES_OPTION) {
						myVA.terminate();
						System.exit(0);
					}
				}
				else	{
//					System.out.println("terminate");
					myVA.terminate();
					System.exit(0);
				}
			}
		});

		//add button functionality
		addCourseButton.addActionListener(	new ActionListener(){
			public void actionPerformed(ActionEvent arg0)
			{
				//Rotem added this condition :-)
				if (blankPlan == true) {
					JOptionPane.showMessageDialog(null, "Please load an existing plan or click \"New Plan\" to begin.");
				} else {	
					try {
						saved = false;
						SelectCoursesGUI_Catalog addCourses = new SelectCoursesGUI_Catalog(StudentMainGUI.this, "add_courses", false, myPlan, myVA);
						
					} catch (InterruptedException e) {
						GUI_Function_Library.exceptionHandler("STUDENTMAINGUI" , e);
					}
				}
			}
		});
		editCourseButton.addActionListener(	new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				if (blankPlan == true) {
					JOptionPane.showMessageDialog(null, "Please load an existing plan or click \"New Plan\" to begin.");
				} else {
					saved = false;
//					RemoveCoursesGUI openMe = new RemoveCoursesGUI(myPlan);
					SelectCoursesGUI_Plan openMe = new SelectCoursesGUI_Plan(StudentMainGUI.this, "move_course", myPlan, myVA);
				}
			}
		});
		auditButton.addActionListener(		new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				//Rotem added this condition :-)
				if (blankPlan == true) {
					JOptionPane.showMessageDialog(null, "Please load an existing plan or click \"New Plan\" to begin.");
				}
				String analysis = myVA.analyseFullPlanCompleteDegree(myPlan.getPlanName());
				
				JTextArea mindyTA = new JTextArea(analysis);
				mindyTA.setSize(740, 490);
				JPanel pane1 = new JPanel();
				pane1.add(mindyTA);
				pane1.setSize(740, 490);
				
				JScrollPane pane2 = new JScrollPane(pane1);
				pane2.setPreferredSize(new Dimension(750, 500));
				
				JPanel mindyPane = new JPanel();
				mindyPane.add(pane2);
				GUI_Function_Library.displayPane("Hello", mindyPane, true);
				
				
				
				
				
//				JFrame myAnalysisFrame = new JFrame();

				JTextArea myJTA = new JTextArea();
				myJTA.setText(analysis);
//				myJTA.setSize(440, 440);
				
				JPanel textPanel = new JPanel();
				textPanel.add(myJTA);
				
				JScrollPane myJSP = new JScrollPane();
				myJSP.add(textPanel);
				myJSP.setPreferredSize(new Dimension(350, 300));
//				myJSP.setSize(460, 460);

				
				JPanel myPanel = new JPanel(new BorderLayout());
				myPanel.add(myJSP, BorderLayout.CENTER);
				myPanel.setSize(480, 480);
				//myJSP.add(myJTA);
//				GUI_Function_Library.displayPane("Audit Report", myPanel, true);
				//myAnalysisFrame.setVisible(true);
				//nothing yet
				//JOptionPane.showMessageDialog(null, "PLEASE ADD FUNCTIONALITY");
			}
		});
		
		
		
		// put everything together
		mainStuPane.add(mainPanel,			BorderLayout.CENTER);
		mainStuPane.add(accountPane,		BorderLayout.NORTH);
		mainStuPane.add(scheduleButtonPane, BorderLayout.WEST);
		mainStuPane.add(feedbackPane,		BorderLayout.SOUTH);
		
		mainStuPane.setPreferredSize(new Dimension(800, 500));
		
		return mainStuPane;
	}
	
	
	
	public void passBack(String cmd, String message)
	{
		System.out.println("---STUDENTMAINGUI: PASSBACK: ");
		if(cmd.equals("add_courses"))
		{
			// process the message
			System.out.println("CA CAW! " +  message);
			String[] data = message.split(",");
			String[] seasonandyear = data[0].split(" ");
			int season = ProjectConstants.getSeasonInt(seasonandyear[0]);
			int year = Integer.parseInt(seasonandyear[1]);
			
			int okay;
			for(int i = 1; i != data.length; i++)
			{
				okay = myVA.addCourseRecord(myPlan.getPlanName(), season, year, new CourseRecord(data[i]));
				if (okay == -1) {
					JOptionPane.showMessageDialog(null, data[i] + " was not added to " + ProjectConstants.getSeasonString(season) + " " + year + ". You may not add duplicate courses to the same semester.");
				} else if (okay == -2) {
					JOptionPane.showMessageDialog(null, data[i] + " could not be added to " + ProjectConstants.getSeasonString(season) + " " + year + ". Unknown error.");
				} else if (okay < 0) {
					JOptionPane.showMessageDialog(null, "Some of the courses you selected could not be loaded. You may only take " + (okay * -1) + " credits per semester.");
					break;
				}
			}
			
			loadButton();
			frame.validate();
		}
		else if(cmd.compareTo("move_course") == 0)
		{
			System.out.println("CA CAW! " +  message);
			String[] data = message.split(" ");
			String[] firstSem = data[0].split(",");
			String[] secondSem = data[3].split(",");
			String courseID = data[1] + " " + data[2];
			
			
			int season1 = Integer.parseInt(firstSem[0]);
			int year1 = Integer.parseInt(firstSem[1]);
			int season2 = Integer.parseInt(secondSem[0]);
			int year2 = Integer.parseInt(secondSem[1]);
			
			CourseRecord tempCR = myVA.getCourseRecord(myPlan.getPlanName(), season1, year1, courseID);
			myVA.removeCourseRecord(myPlan.getPlanName(), season1, year1, courseID);
			myVA.addCourseRecord(myPlan.getPlanName(), season2, year2, tempCR);
			
			loadButton();
			frame.validate();
		}
		else
			System.out.println("cmd : " + cmd + " " + message);
	}
	
	private void loadButton()
	{
		saved = false;
		mainPanel.setVisible(false);
		try {
			myPlan = myVA.getPlan(myPlan.getPlanName());
			JPanel mySchedPane = loadedSchedule( myPlan);
			resetSchedulePane( mySchedPane);
			mainStuPane.add(mySchedPane, BorderLayout.EAST);
			mainStuPane.revalidate();
		} catch (Exception e) {
			GUI_Function_Library.exceptionHandler("Load Plan", e);
		}		
	}
	
}
